package com.ms.server.servlet;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import com.ms.env.EnvUtil;
import com.ms.server.init.DbUpdate;
import com.suyunyou.comm.constants.Constant;
import com.suyunyou.comm.constants.DictCons;
import com.suyunyou.comm.utils.RunSpiderUtil;
import com.system.comm.utils.FrameSpringBeanUtil;
import com.system.comm.utils.FrameTimeUtil;

/**
 * 初始化系统数据的Servlet
 * @author yuejing
 * @date 2016-5-16 下午9:54:12
 * @version V1.0.0
 */
@WebServlet(urlPatterns="/init", description="初始数据", loadOnStartup=1)
public class Init extends HttpServlet {
	private static final long serialVersionUID = 5764818908745849607L;
	private static final Logger LOGGER = LoggerFactory.getLogger(Init.class);

	/**
	 * 初始化方法
	 * @see Servlet#init(ServletConfig)
	 */
	@Override
	public void init(ServletConfig config) throws ServletException {
		LOGGER.info("初始化数据中...");
		long startTime = System.currentTimeMillis();
		Constant.webroot = config.getServletContext().getContextPath();
		config.getServletContext().setAttribute("webroot", Constant.webroot);
		//版本号为年月日[如: 20130126]
		String version = String.format("?version=%s", FrameTimeUtil.parseString(FrameTimeUtil.getTime(), FrameTimeUtil.FMT_YYYYMMDDHH));
		config.getServletContext().setAttribute("version", version);
		config.getServletContext().setAttribute("projectName", EnvUtil.projectName());
		Constant.serviceStartTime = FrameTimeUtil.getTime();
		//初始化字典信息
		DictCons.init(config.getServletContext());
		
		DbUpdate.init();
		
		//启动爬虫
		ThreadPoolTaskExecutor executor = FrameSpringBeanUtil.getBean(ThreadPoolTaskExecutor.class);
		executor.execute(new Runnable() {
			
			@Override
			public void run() {
				try {
					// 延迟10s
					Thread.sleep(10 * 1000);
				} catch (InterruptedException e) {
				}
				RunSpiderUtil.init();
			}
		});
		
		LOGGER.info("初始化资源花费" + (System.currentTimeMillis() - startTime) + "毫秒!");
	}


}
